package com.wzq.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzq.dao.pojo.*;
import com.wzq.service.IDurationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yzc
 * @since 2022-08-31
 */
@RestController
@RequestMapping("/admin/duration")
public class AdminDurationController extends GetSome {

    @Autowired
    private IDurationService iDurationService;

    @RequestMapping("/list")        //添加
    public R list(@RequestBody PageBean pageBean) {
        String query = pageBean.getQuery().trim();
        Page<Duration> page = new Page<>(pageBean.getPageNum(), pageBean.getPageSize());
        Page<Duration> pageResult = iDurationService.page(page, "".equals(query)?null:
                new QueryWrapper<Duration>().in("p_id",searchByPname(query) ));
        Map<String, Object> map = new HashMap<>();
        //        添加用户名称和项目名称
        List<Duration> durations = new ArrayList<>();
        for (Duration duration : pageResult.getRecords()) {
            duration.setP_name(getP_name(duration.getP_id()));
            durations.add(duration);
        }
        map.put("DurationList", durations);
        map.put("total", pageResult.getTotal());
        return R.ok(map);
    }

    @RequestMapping("/save")        //添加修改
    public R save(@RequestBody Duration duration) {
        if (duration.getId() == null || duration.getId() == -1) {
            iDurationService.save(duration);
        } else {
            iDurationService.saveOrUpdate(duration);
        }
        return R.ok();
    }

    @GetMapping("/{id}")            //单个回显
    public R findById(@PathVariable(value = "id") Integer id) {
        Duration duration = iDurationService.getById(id);
        //        获得用户名称和项目名称
        duration.setP_name(getP_name(duration.getP_id()));
        Map<String, Object> map = new HashMap<>();
        map.put("duration", duration);
        return R.ok(map);
    }

    @GetMapping("/delete/{id}")     //删除
    public R delete(@PathVariable(value = "id") Integer id) {
        boolean b = iDurationService.removeById(id);
        if (b){
            return R.ok("删除成功");
        }
        return R.error("删除失败");
    }
}

